package com.sojson.util.security.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.sojson.config.exception.TransErrorCode;
import com.sojson.constant.ConstantByMap;
import com.sojson.util.filter.FilterUtil;

/**
 * 判断用户有没有登录
 * 
 * @author liu
 * @date 2020-11-02
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // // 如果是相关目录return true
        // if (ShiroFilterUtils.isOpenUrl((HttpServletRequest) request)) {
        // return Boolean.TRUE;
        // }

        // 判断有没有登录或者记住我
        Subject subject = getSubject(request, response);
        if (subject.isAuthenticated() || subject.isRemembered()) {
            return Boolean.TRUE;
        }

        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        responseDateTouch(request, response, TransErrorCode.NOT_LOGIN, ConstantByMap.CONTROLLER_URL_OPEN_LOGIN_URL_ALL);
        return Boolean.FALSE;
    }

    /**
     * 对结果进行处理并更新Session
     * 
     * @param request
     * @param response
     * @param code 错误代码
     * @param url 要跳转的路径
     * @throws IOException
     */
    private void responseDateTouch(ServletRequest request, ServletResponse response, TransErrorCode code, String url)
        throws IOException {
        FilterUtil.responseDateTouch(request, response, code, url);
    }

}